import { defineStore } from 'pinia';
import { deleteCGMessage } from '@/api/modules/rbac/dcp/message_management';

export const useMessageListStore = defineStore('messageList', () => {
  const messageList = ref<any[]>([{ id: 1, phone: '', message: '', mid: '' }]);
  const count = ref<number>(1);
  const addCount = () => {
    count.value++;
  };
  const addList = () => {
    count.value++;
    const newData = { id: count.value, phone: '', message: '', mid: '' };
    messageList.value.push(newData);
  };
  const deleteList = async (id: number) => {
    messageList.value.forEach(async (list: any) => {
      if (list.id === id) {
        if (list.mid !== '') {
          await deleteCGMessage(list.mid);
        }
      }
    });
    messageList.value = messageList.value.filter(item => id !== item.id);
  };
  const getMessageList = () => {
    return messageList;
  };
  const setMessageList = (data: any) => {
    for (let i = 0; i < messageList.value.length; i++) {
      if (messageList.value[i].id === data.id) {
        messageList.value[i].phone = data.phone;
        messageList.value[i].message = data.message;
      }
    }
  };
  const reCount = () => {
    count.value = 1;
  };
  const reList = () => {
    messageList.value = [{ id: 1, phone: '', message: '', mid: '' }];
    reCount();
  };
  const delListItem = (id: number) => {
    messageList.value.forEach(async (list: any) => {
      if (list.id === id) {
        if (list.mid !== '') {
          await deleteCGMessage(list.mid);
        }
      }
    });
    messageList.value = messageList.value.filter(message => message.id !== id);
  };
  const addItems = (items: any[]) => {
    messageList.value = [];
    count.value = 0;
    items.forEach((item: any) => {
      if (item.isDelete === 0) {
        count.value++;
        messageList.value.push({ id: count.value, phone: item.phoneNumber, message: item.messageContent, mid: item.id });
      }
    });
  };
  return {
    count,
    addCount,
    messageList,
    addList,
    deleteList,
    getMessageList,
    setMessageList,
    reList,
    delListItem,
    addItems,
  };
}, {
  persist: true,
});
